package com.cn.qgx428.orderingmeal;

import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.qgx428.orderingmeal.adapter.OrderDetailAdapter;
import com.cn.qgx428.orderingmeal.adapter.RBaseAdapter;
import com.cn.qgx428.orderingmeal.dialog.CommentDialog;
import com.cn.qgx428.orderingmeal.myClass.Food;
import com.cn.qgx428.orderingmeal.myClass.Order;
import com.cn.qgx428.orderingmeal.myClass.OrderDetailInfo;
import com.cn.qgx428.orderingmeal.myClass.Shop;
import com.cn.qgx428.orderingmeal.viewHolder.RViewHolder;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

public class OrderDetail extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "OrderDetail";

    private String userID;
    private String orderID;

    private ImageView back;

    private TextView text_orderID;
    private TextView text_orderPrice;

    private RecyclerView recyclerView;
    private OrderDetailAdapter adapter;
    private List<OrderDetailInfo> orderInfos;

    private TextView comment;

    private List<Shop> shopList; // 用于选择所评价的店铺
    private RecyclerView chooseRecycler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);

        Bmob.initialize(this,"1b925fe2ccbb402f4034a3e28c31ad93");

        init();
        getData();
    }

    private void getData() {
        BmobQuery<Order> query = new BmobQuery<Order>();
        Log.d(TAG, "getData: "+orderID);
        query.getObject(orderID, new QueryListener<Order>() {
            @Override
            public void done(Order order, BmobException e) {
                if (e == null){
                    text_orderPrice.setText("￥ "+String.valueOf(order.getTotalPrice()));
                    //解析订单数据
                    String[] foodIDS  = order.getFoodsID().split(",");
                    Log.d(TAG, "获取食物ID: "+foodIDS.length);
                    final String[] foodTotalPrice = order.getItemTotalPrice().split(",");
                    List<BmobQuery<Food>> queries = new ArrayList<BmobQuery<Food>>();
                    for (int i=0 ; i<foodIDS.length; i++){
                        BmobQuery<Food> query = new BmobQuery<Food>();
                        query.addWhereEqualTo("objectId" , foodIDS[i]);
                        Log.d(TAG, "食物ID : "+foodIDS[i]);
                        queries.add(query);
                    }
                    Log.d(TAG, "查询数据队列长度 ："+queries.size());

//                    BmobQuery<Food> query1 = new BmobQuery<Food>();
//                    query1.addWhereEqualTo("objectId","itENWTTW");
//                    BmobQuery<Food> query2 = new BmobQuery<Food>();
//                    query2.addWhereEqualTo("objectId","YSXB4bb4");
//                    queries.add(query1);
//                    queries.add(query2);
                    BmobQuery<Food> query = new BmobQuery<Food>();
                    query.or(queries);
                    query.include("shop");
                    query.findObjects(new FindListener<Food>() {
                        @Override
                        public void done(List<Food> list, BmobException e) {
                            if (e==null){
                                orderInfos = new ArrayList<OrderDetailInfo>();
                                for (int i=0 ; i <list.size(); i++){
                                    Food food = list.get(i);
                                    OrderDetailInfo orderInfo = new OrderDetailInfo();
                                    orderInfo.setFoodName(food.getName());
                                    orderInfo.setFoodPrice(food.getPrice());
                                    orderInfo.setFoodTotalPrice(foodTotalPrice[i]);
                                    orderInfos.add(orderInfo);

                                    //将出现的店铺记录
                                    Shop shop = food.getShop();
                                    Boolean isExist = false;
                                    for(int j=0 ; j<shopList.size(); j++){
                                        if (shopList.get(j).getObjectId().equals(shop.getObjectId()) ){
                                            isExist = true;
                                            break;
                                        }
                                    }
                                    if (!isExist){
                                        shopList.add(shop);
                                    }
                               }
                                Log.d(TAG, "获取出现的店铺 ："+shopList.size());

                            adapter = new OrderDetailAdapter(OrderDetail.this , orderInfos, R.layout.orderdetail_item);
                            recyclerView.setAdapter(adapter);
                            } else {
                                Log.d(TAG, "done2: "+e.getErrorCode()+e.getMessage());
                            }
                        }
                    });

                } else {
                    Toast.makeText(OrderDetail.this, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "获取订单详情 :"+e.getErrorCode()+e.getMessage());
                }
            }
        });
    }

    private void init() {
        userID = getIntent().getStringExtra("userID");
        orderID = getIntent().getStringExtra("orderID");

        back = (ImageView)findViewById(R.id.orderDetail_back);
        back.setOnClickListener(this);
        text_orderID = (TextView) findViewById(R.id.orderDetail_no);
        text_orderID.setText(orderID);
        text_orderPrice = (TextView) findViewById(R.id.orderDetail_orderPrice);
        recyclerView = (RecyclerView)findViewById(R.id.orderDetai_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        comment = (TextView) findViewById(R.id.orderDetail_comment);
        comment.setOnClickListener(this);
        shopList = new ArrayList<Shop>();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.orderDetail_back:
                finish();
                break;
            case R.id.orderDetail_comment:
                //选择评价的店铺
                showChooseCommentDialog();
        }
    }

    private void showChooseCommentDialog() {
        final Dialog dialog = new Dialog(this , R.style.Theme_Light_Dialog);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.orderdetail_choose_comment_dialog,null);
        //获得dialog的window窗口
        Window window = dialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        window.setWindowAnimations(R.style.dialogStyle);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        dialog.setContentView(dialogView);
        chooseRecycler = (RecyclerView)dialogView.findViewById(R.id.orderDetail_chooseDialogRecycler);
        chooseRecycler.setLayoutManager(new LinearLayoutManager(this));
        chooseRecycler.setAdapter(new RBaseAdapter(this ,shopList,R.layout.orderdetail_choose_comment_item) {
            @Override
            public void convert(RViewHolder holder, Object item) {
                final Shop shop = (Shop)item;

                TextView option = holder.getView(R.id.orderDetail_chooseDialog_optionText);
                ImageView optionPic = holder.getView(R.id.orderDetail_chooseDialog_img);
                LinearLayout optionLayout = holder.getView(R.id.orderDetail_chooseDialog_optionLayout);

                option.setText(shop.getName());
                Picasso.with(getmContext()).load(shop.getImg().getFileUrl()).into(optionPic);
                optionLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //弹出评论框
                        showCommentDialog(shop);
                        dialog.dismiss();
                    }
                });
            }

        });

        dialog.show();
    }

    private void showCommentDialog(Shop shop) {
        CommentDialog dialog = new CommentDialog(this,shop,userID);
        dialog.show();
        Window window = dialog.getWindow();
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
